package framework.jiekou.sub;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.gong.movie.ui.R;
import framework.annotation.ClickMethod;
import framework.annotation.InjectView;
import framework.config.RequestCode;
import framework.config.ResultCode;
import framework.database.callback.DBCallBack;
import framework.http.bean.HttpTask;
import framework.http.callback.HttpCallBack;
import framework.jiekou.Act;
import framework.manage.ManageAct;
import framework.utils.ManagerUitls;
import framework.utils.NetUtils;

public class ActImpl extends ViewSettingImpl implements Act, HttpCallBack {
	private Act act;

	public ActImpl(Act act, Context context) {
		super(context);
		this.act = act;
	}

	@Override
	public void onCreateAct(Bundle savedInstanceState) {
		try {
			// 强制竖屏
			getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			// 在ActivityManager中注册
			ManageAct.getInstance().addAct(getActivity());
			// 异步网络请求
			getAct().onCreateAct(savedInstanceState);
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void onStartAct() {
		try {
			getAct().onStartAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void onResumeAct() {
		try {
			// 恢复暂时储存的数据
			getAct().onDateRecovery();
			getAct().onResumeAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void onDateRecovery() {

	}

	@Override
	public void onRestartAct() {
		try {
			getAct().onRestartAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void onPauseAct() {
		try {
			// 清理并暂时缓存数据
			getAct().onDateClear();
			getAct().onPauseAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void onDateClear() {
	}

	@Override
	public void onStopAct() {
		try {
			getAct().onStopAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void onDestroyAct() {
		try {
			// 移除act
			ManageAct.getInstance().deleteAct(getActivity());
			getAct().onDestroyAct();
		} catch (Exception e) {
			exception(e);
		}
	}

	@Override
	public void setContentView(int layoutResID) {
		View inflate = inflate(layoutResID);
		getAct().setContentView(inflate);
	}

	@Override
	public void setContentView(View view) {
		inject();
	}

	@Override
	public void setContentView(View view, ViewGroup.LayoutParams params) {
		inject();
	}

	private void clickMethod() {
		Method[] methods = getActivity().getClass().getDeclaredMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			Annotation[] annotations = method.getAnnotations();
			for (Annotation annotation : annotations) {
				Class type = annotation.annotationType();
				if (type == ClickMethod.class) {
					ClickMethod methodAnno = (ClickMethod) annotation;
					int[] values = methodAnno.value();
					SparseArray<Method> clickMethods = getClickMethods();
					for (int viewID : values) {
						clickMethods.put(viewID, method);
						View view = getActivity().findViewById(viewID);
						if (view != null) {
							view.setOnClickListener(getOnClickListener());
						}
					}
				}
			}
		}
	}

	@Override
	public void setLayout(int layoutResID) {
		setContentView(layoutResID);
	}

	private void inject() {
		injectView();
		clickMethod();
	}

	private void injectView() {
		Activity activity = getActivity();
		Field[] fields = activity.getClass().getDeclaredFields();
		for (Field field : fields) {
			InjectView annotation = field.getAnnotation(InjectView.class);
			if (annotation != null) {
				int value = annotation.value();
				View view = getActivity().findViewById(value);
				try {
					field.setAccessible(true);
					field.set(activity, view);
				} catch (Exception e) {
					log("异常:fieldName:" + field.getName());
					exception(e);
				}
			}
		}
	}

	@Override
	public AlertDialog getAlertDialog() {
		AlertDialog myDialog = getAlertDialogBuilder().create();
		myDialog.show();
		// LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.MATCH_PARENT);
		myDialog.getWindow().setContentView(inflate(R.layout.progress));
		myDialog.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					return true;
				}
				return false;
			}
		});
		return myDialog;
	}

	@Override
	public void dialogCancel(AlertDialog dialog) {
		if (dialog != null) {
			dialog.cancel();
			dialog = null;
		}
	}

	@Override
	public OnClickListener getOnClickListener() {
		return getAct().getOnClickListener();
	}

	@Override
	public DBCallBack getDBCallBack() {
		return getAct().getDBCallBack();
	}

	@Override
	public HttpCallBack getHttpCallBack() {
		return getAct().getHttpCallBack();
	}

	@Override
	public void openAct(Intent intent) {
		getActivity().startActivity(intent);
	}

	@Override
	public void openAct(Class newActClass) {
		openAct(new Intent(getActivity(), newActClass));
	}

	@Override
	public void openActForResult(Class newActClass, int requestCode) {
		openActForResult(new Intent(getActivity(), newActClass), requestCode);
	}

	@Override
	public void openActForResult(Class newActClass, RequestCode code) {
		openActForResult(newActClass, code.ordinal());
	}

	@Override
	public void openActForResult(Intent intent, int requestCode) {
		getActivity().startActivityForResult(intent, requestCode);
	}

	@Override
	public void openActForResult(Intent intent, RequestCode code) {
		openActForResult(intent, code.ordinal());
	}

	@Override
	public void animAlpha() {
		getActivity().overridePendingTransition(R.anim.alpha0to100, R.anim.alpha100to0);
	}

	@Override
	public void animScaleOpen() {
		getActivity().overridePendingTransition(R.anim.scale0to100, R.anim.scale100to100);
	}

	@Override
	public void animScaleClose() {
		getActivity().overridePendingTransition(R.anim.scale100to100, R.anim.scale100to0);
	}

	@Override
	public void animTranslateTopIn() {
		getActivity().overridePendingTransition(R.anim.translateyf100to0, R.anim.translatey0to100);
	}

	@Override
	public void animTranslateBottomIn() {
		getActivity().overridePendingTransition(R.anim.translatey100to0, R.anim.translatey0tof100);
	}

	@Override
	public void animTranslateRightIn() {
		getActivity().overridePendingTransition(R.anim.translatex100to0, R.anim.translatex0tof100);
	}

	@Override
	public void animTranslateLeftIn() {
		getActivity().overridePendingTransition(R.anim.translatexf100to0, R.anim.translatex0to100);
	}

	@Override
	public void closeAct() {
		getActivity().finish();
	}

	@Override
	public void closeAct(int resultCode) {
		getActivity().setResult(resultCode);
		closeAct();
	}

	@Override
	public void closeAct(int resultCode, Intent data) {
		getActivity().setResult(resultCode, data);
		closeAct();
	}

	@Override
	public void closeActForResultOk() {
		closeAct(resultOk());
	}

	@Override
	public void closeActForResultCanceled() {
		closeAct(resultCancel());
	}

	@Override
	public void closeActForResultError() {
		closeAct(resultError());
	}

	@Override
	public void closeActForResultOk(Intent data) {
		closeAct(resultOk(), data);
	}

	@Override
	public void inputHidden(EditText et) {
		InputMethodManager imm = getInputMethodManager();
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
	}

	@Override
	public void inputShow(EditText et) {
		InputMethodManager imm = getInputMethodManager();
		imm.showSoftInput(et, 0);
	}

	private InputMethodManager getInputMethodManager() {
		return ManagerUitls.getInputMethodManager(getContext());
	}

	public void toast(final String msg) {
		// 主线程执行toast
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (!TextUtils.isEmpty(msg)) {
					Toast.makeText(getContext(), msg, 1000).show();
				}
			}
		});
	}

	@Override
	public void toast(int resID) {
		toast(getActivity().getString(resID));
	}

	boolean isExit = false;
	private SparseArray<Method> methods;

	@Override
	public void alertExit() {
		if (!isExit) {
			isExit = true;
			toast(R.string.logout_app_notice);

			final Timer timer = new Timer();
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					isExit = false;
					timer.cancel();
				}
			}, 2000);
		} else {
			ManageAct manager = ManageAct.getInstance();

			ArrayList<Activity> allAct = manager.getAllAct();
			for (int i = 0; i < allAct.size(); i++) {
				Activity activity = allAct.get(i);
				activity.finish();
			}

			manager.clear();
		}
	}

	// public void alertExit() {
	// AlertDialog.Builder ab = getAlertDialogBuilder();
	// ab.setTitle("提示");
	// ab.setMessage("确定退出吗?");
	// ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog, int which) {
	// // Intent it = new Intent(BaseAct.this, MainService.class);
	// // getApplicationContext().stopService(it);
	//
	// ManageAct manager = ManageAct.getInstance();
	//
	// ArrayList<Activity> allAct = manager.getAllAct();
	// for (int i = 0; i < allAct.size(); i++) {
	// Activity activity = allAct.get(i);
	// activity.finish();
	// }
	//
	// manager.clear();
	//
	// // android.os.Process.killProcess(android.os.Process.myPid());
	// }
	// });
	// ab.setNegativeButton("取消", null);
	// ab.setOnKeyListener(new OnKeyListener() {
	//
	// public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	// {
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// return true;
	// }
	// return false;
	// }
	// });
	// ab.create().show();
	// }

	@Override
	public void setClick(int viewID) {
		setClick(getActivity().findViewById(viewID));
	}

	@Override
	public void setClick(int viewID, View view) {
		if (view != null) {
			setClick(view.findViewById(viewID));
		}
	}

	@Override
	public void setClick(View view) {
		if (view != null) {
			view.setOnClickListener(getOnClickListener());
		}
	}

	@Override
	public LinearLayout findLinearLayoutById(int id) {
		return (LinearLayout) getActivity().findViewById(id);
	}

	@Override
	public ListView findListViewById(int id) {
		return (ListView) getActivity().findViewById(id);
	}

	@Override
	public Button findButtonById(int id) {
		return (Button) getActivity().findViewById(id);
	}

	@Override
	public ProgressBar findProgressBarById(int id) {
		return (ProgressBar) getActivity().findViewById(id);
	}

	@Override
	public ImageView findImageViewById(int id) {
		return (ImageView) getActivity().findViewById(id);
	}

	@Override
	public RelativeLayout findRelativeLayoutById(int id) {
		return (RelativeLayout) getActivity().findViewById(id);
	}

	@Override
	public TextView findTextViewById(int id) {
		return (TextView) getActivity().findViewById(id);
	}

	@Override
	public CheckBox findCheckBoxById(int id) {
		return (CheckBox) getActivity().findViewById(id);
	}

	@Override
	public FrameLayout findFrameLayoutById(int id) {
		return (FrameLayout) getActivity().findViewById(id);
	}

	@Override
	public ImageButton findImageButtonById(int id) {
		return (ImageButton) getActivity().findViewById(id);
	}

	@Override
	public EditText findEditTextById(int id) {
		return (EditText) getActivity().findViewById(id);
	}

	public void viewShow(int id) {
		viewShow(getActivity().findViewById(id));
	}

	public void viewGone(int id) {
		viewGone(getActivity().findViewById(id));
	}

	public boolean onKeyDownBackNormal(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			closeAct();
			animTranslateLeftIn();
			return true;
		}
		return false;
	}

	public boolean onKeyDownBackExit(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			alertExit();
			return true;
		}
		return false;
	}

	@Override
	public Act getAct() {
		return act;
	}

	@Override
	public void setAct(Act act) {
		this.act = act;
	}

	@Override
	public Activity getActivity() {
		return getAct().getActivity();
	}

	@Override
	public Builder getAlertDialogBuilder() {
		return new AlertDialog.Builder(getActivity());
	}

	private int dealResultCode(ResultCode code) {
		return code.ordinal() - 1;
	}

	@Override
	public int resultOk() {
		return dealResultCode(ResultCode.RESULT_OK);
	}

	@Override
	public int resultCancel() {
		return dealResultCode(ResultCode.RESULT_CANCELED);
	}

	@Override
	public int resultError() {
		return dealResultCode(ResultCode.RESULT_ERROR);
	}

	@Override
	public int resultDelete() {
		return dealResultCode(ResultCode.RESULT_DELETE);
	}

	@Override
	public RequestCode requestCode(int requestCode) {
		try {
			return RequestCode.values()[requestCode];
		} catch (Exception e) {
			exception(e);
			return RequestCode.NO;
		}

	}

	@Override
	public ResultCode resultCode(int resultCode) {
		try {
			return ResultCode.values()[resultCode + 1];
		} catch (Exception e) {
			exception(e);
			return null;
		}
	}

	@Override
	public boolean hasNet() {
		return NetUtils.hasNet(getContext());
	}

	@Override
	public void toastNoNet() {
		toast("现在网络不可用。请先设置网络");
	}

	@Override
	public void httpTaskFinish(final HttpTask task) {
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				getAct().onHttpCallBack(task);
			}
		});
	}

	@Override
	public void onHttpCallBack(HttpTask task) {

	}

	@Override
	public void dbTaskFinish(final int dbTaskType, final Object data) {
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				getAct().onDbCallBack(dbTaskType, data);
			}
		});
	}

	@Override
	public void onDbCallBack(int dbTaskType, Object data) {

	}

	@Override
	public void onClick(View view) {
		Method method = getMethods().get(view.getId());
		try {
			if (method != null) {
				method.setAccessible(true);
				method.invoke(getActivity(), view);
			}
		} catch (Exception e) {
			log("异常：methodName:" + method.getName());
			exception(e);
		}
	}

	private SparseArray<Method> getClickMethods() {
		if (methods == null) {
			methods = new SparseArray<Method>();
		}
		return methods;
	}

	private SparseArray<Method> getMethods() {
		if (methods == null) {
			methods = new SparseArray<Method>();
		}

		if (methods.size() <= 0) {
			clickMethod();
		}

		return methods;
	}

}
